package com.fyyg.wechat.util.wechat;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.InternalContextAdapterImpl;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.RuntimeInstance;
import org.apache.velocity.runtime.parser.node.SimpleNode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fyyg.common.exceptions.StandardException;
import com.google.common.base.Strings;

public class VelocityHelper
{

	static RuntimeInstance _rntIns = new RuntimeInstance();

    public static String buildVelocityContent(String vmTemplateContent,
            Object obj)
    {

        if (Strings.isNullOrEmpty(vmTemplateContent))
        {
            return StringUtils.EMPTY;
        }
        JSONObject json = null;
        if (obj == null)
        {
            json = new JSONObject();
        }
        else
        {
            json = (JSONObject) JSON.toJSON(obj);
        }

        SimpleNode _smplNd = preCompileSimpleNode(vmTemplateContent, _rntIns);

        InternalContextAdapterImpl ica = initialIca(json, _smplNd);
        StringWriter sw = new StringWriter();
        try
        {
            _smplNd.render(ica, sw);
        }
        catch (MethodInvocationException | ParseErrorException
                | ResourceNotFoundException | IOException e)
        {
            throw new StandardException(
                    ErrorConstants.ERROR_SERVICE_FATAL, "模板执行失败", e);
        }
        return sw.toString();
    }

    /**
     * @param json
     * @param _smplNd
     * @return
     */
    private static InternalContextAdapterImpl initialIca(JSONObject json,
            SimpleNode _smplNd)
    {
        InternalContextAdapterImpl ica = new InternalContextAdapterImpl(
                new VelocityContext(json));
        ica.put("StringUtils", new StringUtils());
        ica.put("StringHelper", new StringHelper());
        ica.put("newline", "\n");
        _smplNd.init(ica, _rntIns);
        return ica;
    }

    private static SimpleNode preCompileSimpleNode(String content,
            RuntimeInstance _rntIns)
    {
        SimpleNode _smplNd = null;
        try {
			_smplNd = _rntIns.parse(content, "ve");
		} catch (org.apache.velocity.runtime.parser.ParseException e) {
			throw new com.fyyg.common.exceptions.StandardException(
                    ErrorConstants.ERROR_SERVICE_FATAL, "模板解析失败", e);
		}

        return _smplNd;
    }

}
